<template>
	<div class="table-box">
		<ProTable ref="proTable" title="文件管理" :columns="columns" :requestApi="getFileList" selectId="id">
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<el-button type="primary" :icon="Setting" @click="openDrawer(2)">云存储配置</el-button>
				<el-button type="primary" :icon="UploadFilled" @click="openDrawer(1)">上传文件</el-button>
				<el-button
					type="danger"
					:icon="Delete"
					plain
					@click="batchDelete(scope.selectedListIds as unknown as number[])"
					:disabled="!scope.isSelected"
				>
					批量删除
				</el-button>
			</template>

			<!-- 表格操作 -->
			<template #operation="scope">
				<el-button type="danger" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
			</template>
		</ProTable>
		<!-- 新增和编辑 -->
		<zhy-pop-form :drawerTitle="drawerTitle" ref="popRef">
			<template #formbox>
				<form-box
					:itemForm="itemForm"
					:submitting="submitting"
					:is-show-btn="false"
					v-if="handleType === 1"
					:closeForm="cancelForm"
					:submit-form="submitForm"
					ref="formbox"
				>
				</form-box>

				<form-box
					:itemForm="itemForm"
					:submitting="submitting"
					v-else
					:closeForm="cancelForm"
					:submit-form="submitForm"
					ref="formbox"
				>
				</form-box></template
		></zhy-pop-form>
	</div>
</template>

<script setup lang="tsx" name="user">
import { ref, computed, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { ZhyPopForm, ProTable, FormBox } from '@/components';
import { useCheckout } from '@/hooks';

import { FromBoxProps } from '@/components/FormBox/interface';
import { ColumnProps } from '@/components/ProTable/interface';
import { useHandleData } from '@/hooks/useHandleData';
import { UploadFilled, Delete, Setting } from '@element-plus/icons-vue';
import { getFileList, saveConfig, deleteFileBatch, getOssConfig } from '@/api/modules/sys';
// const globalStore = GlobalStore();
// 用户操作权限
// const permissions = computed(() => globalStore.userInfo.role);
const { getValidRule } = useCheckout();

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 表格配置项
const columns: ColumnProps[] = [
	{ type: 'selection', fixed: 'left' },
	{ prop: 'id', label: 'ID' },
	{ prop: 'url', label: 'URL地址', width: 800 },
	{ prop: 'createDate', label: '创建时间' },
	{
		prop: 'operation',
		label: '操作',
		fixed: 'right',
		isShow: true
	}
];

// 删除用户信息
const deleteAccount = async (params: any) => {
	await useHandleData(deleteFileBatch, [params?.id], `删除【${params.id}】`);
	proTable.value.getTableList();
};

// 批量删除(表格组件需要设置selectId)
const batchDelete = async (id: number[]) => {
	await useHandleData(deleteFileBatch, id, `删除${id.length}条数据`);
	// 清除表格复选框之前选中状态
	proTable.value.clearSelection();
	// 刷新数据
	proTable.value.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const popRef = ref<InstanceType<typeof ZhyPopForm>>();
const formbox = ref<InstanceType<typeof FormBox>>();
const ossConfig = ref<any>({});
const handleType = ref(1);
const drawerTitle = ref<string>('上传文件');

const openDrawer = async (type: number) => {
	popRef.value!.visible = true;
	handleType.value = type;
	if (type === 2) {
		nextTick(() => {
			formbox.value!.formParam = Object.assign(formbox.value!.formParam, {
				...ossConfig.value,
				types: ossConfig.value?.type
			});
		});
	}
};

// 提交表单
const submitting = ref(false);

const submitForm = (): void => {
	const params: any = formbox.value!.formParam;

	submitting.value = true;
	// 新增
	if (handleType.value === 2) {
		saveM({
			...ossConfig.value,
			...params,
			type: params?.types
		});
	}
};

// 取消
const cancelForm = () => {
	popRef.value!.visible = false;
};

const saveM = (params: any): void => {
	saveConfig(params)
		.then(() => {
			ElMessage.success('配置成功');
			submitting.value = false;
			popRef.value!.visible = false;
		})
		.catch(() => {
			submitting.value = false;
		});
};

// 初始化菜单类型数据
const options = [
	{
		label: '七牛云',
		value: 1
	},
	{
		label: '阿里云',
		value: 2
	},
	{
		label: '腾讯云',
		value: 3
	}
];
const menuType = ref(1);
const itemForm = computed(() => {
	let itemForm: FromBoxProps[] = [
		// prop 目前不用type字段，会有冲突
		{
			prop: 'file',
			label: '文件',
			form: { type: 'ZhyUploadFile' },
			rules: getValidRule({ message: '文件' })
		}
	];

	if (handleType.value === 2) {
		itemForm = [
			{
				prop: 'types',
				label: '存储类型',
				enum: options,
				form: {
					el: 'radio-group',
					defaultValue: menuType.value
				},
				changeForm: (val: any) => {
					menuType.value = val;
				},
				rules: { required: true, trigger: 'blur' }
			},
			{
				prop: menuType.value === 1 ? 'qiniuDomain' : menuType.value === 2 ? 'aliyunDomain' : 'qcloudDomain',
				label: '域名',
				form: { el: 'input', props: {} },
				rules: getValidRule({ message: '域名' })
			},
			{
				prop: menuType.value === 1 ? 'qiniuPrefix' : menuType.value === 2 ? 'aliyunPrefix' : 'qcloudPrefix',
				label: '路径前缀',
				form: { el: 'input', props: {} },
				rules: getValidRule({ message: '路径前缀' })
			},
			{
				prop: 'qiniuAccessKey',
				label: 'AccessKey',
				form: { el: 'input', props: {} },
				rules: getValidRule({ message: 'AccessKey' }),
				hidden: menuType.value !== 1
			},
			{
				prop: 'qiniuSecretKey',
				label: 'SecretKey',
				form: { el: 'input', props: {} },
				rules: getValidRule({ message: 'SecretKey' }),
				hidden: menuType.value !== 1
			},
			{
				prop: 'qiniuBucketName',
				label: '空间名',
				form: { el: 'input', props: {} },
				rules: getValidRule({ message: '空间名' }),
				hidden: menuType.value !== 1
			},
			{
				prop: 'aliyunEndPoint',
				label: 'EndPoint',
				form: { el: 'input', props: { placeholder: '阿里云EndPoint' } },
				rules: getValidRule({ message: 'EndPoint' }),
				hidden: menuType.value !== 2
			},
			{
				prop: 'aliyunAccessKeyId',
				label: 'AccessKeyId',
				form: { el: 'input', props: { placeholder: '阿里云AccessKeyId' } },
				rules: getValidRule({ message: 'AccessKeyId' }),
				hidden: menuType.value !== 2
			},
			{
				prop: 'aliyunAccessKeySecret',
				label: 'AccessKeySecret',
				form: { el: 'input', props: { placeholder: '阿里云AccessKeySecret' } },
				rules: getValidRule({ message: 'AccessKeySecret' }),
				hidden: menuType.value !== 2
			},
			{
				prop: 'aliyunBucketName',
				label: 'BucketName',
				form: { el: 'input', props: { placeholder: '阿里云BucketName' } },
				rules: getValidRule({ message: 'BucketName' }),
				hidden: menuType.value !== 2
			},
			{
				prop: 'qcloudAppId',
				label: '腾讯云AppId',
				form: { el: 'input', props: { placeholder: '腾讯云AppId' } },
				rules: getValidRule({ message: '腾讯云AppId' }),
				hidden: menuType.value !== 3
			},
			{
				prop: 'qcloudSecretId',
				label: '腾讯云SecretId',
				form: { el: 'input', props: { placeholder: '腾讯云SecretId' } },
				rules: getValidRule({ message: '腾讯云SecretId' }),
				hidden: menuType.value !== 3
			},
			{
				prop: 'qcloudSecretKey',
				label: '腾讯云SecretKey',
				form: { el: 'input', props: { placeholder: '腾讯云SecretKey' } },
				rules: getValidRule({ message: '腾讯云SecretKey' }),
				hidden: menuType.value !== 3
			},
			{
				prop: 'qcloudBucketName',
				label: '腾讯云BucketName',
				form: { el: 'input', props: { placeholder: '腾讯云BucketName' } },
				rules: getValidRule({ message: '腾讯云BucketName' }),
				hidden: menuType.value !== 3
			},
			{
				prop: 'qcloudRegion',
				label: 'Bucket所属地区',
				form: { el: 'input', props: { placeholder: '如：sh（可选值 ，华南：gz 华北：tj 华东：sh）' } },
				rules: getValidRule({ message: 'Bucket所属地区' }),
				hidden: menuType.value !== 3
			}
		];
	}
	return itemForm;
});
onMounted(() => {
	getOssConfig().then((res: any) => {
		console.log(res);
		ossConfig.value = res?.config;
	});
});
</script>
